//
//  CustomAlertView.m
//  BiXuan
//
//  Created by 王森林 on 2018/7/21.
//  Copyright © 2018年 BSNL. All rights reserved.
//

#import "CustomAlertView.h"

@interface CustomAlertView()

@property (nonatomic, strong) void (^btnClickCallback)(NSInteger index);

@end

@implementation CustomAlertView


-(void)dealloc{
    NSLog(@"=========%@", NSStringFromClass(self.class));
    self.delegate = nil;
}

+ (CustomAlertView *)alertViewWithTitle:(NSString *)title
                            message:(NSString *)message
                      btnTagClicked:(void(^)(NSInteger btnIndex))indexClicked
                  cancelButtonTitle:(NSString *)cancelButtonTitle
                  otherButtonTitles:(NSString *)otherButtonTitles, ...NS_REQUIRES_NIL_TERMINATION{
    
    CustomAlertView *ret = nil;
    if(otherButtonTitles) {
        ret = [[CustomAlertView alloc] initWithTitle:title
                                         message:message
                                        delegate:self
                               cancelButtonTitle:cancelButtonTitle
                               otherButtonTitles:otherButtonTitles, nil];
        
        va_list vl;
        va_start(vl, otherButtonTitles);
        NSString *arg = va_arg(vl, NSString*);
        if(arg != nil){
            [ret addButtonWithTitle:arg];
        }
        while(arg) {
            arg = va_arg(vl, NSString*);
            if(arg != nil){
                [ret addButtonWithTitle:arg];
            }
        }
        va_end(vl);
    } else {
        ret = [[CustomAlertView alloc] initWithTitle:title
                                         message:message
                                        delegate:self
                               cancelButtonTitle:cancelButtonTitle
                               otherButtonTitles:nil];
    }
    
    ret.btnClickCallback = indexClicked;
    ret.delegate = ret;
    return ret;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.delegate = nil;
    if(self.btnClickCallback) {
        self.btnClickCallback(buttonIndex);
        
        self.btnClickCallback = nil;
    }
}

@end
